/**
 * Agent Worker
 * 
 * Worker script for executing agent queries in parallel
 */

// Declare self as Worker to prevent TypeScript errors
declare var self: Worker;

import { query } from '@anthropic-ai/claude-agent-sdk';
import { logger } from '@/utils/logger';
import type { AgentOptions } from '@/types';

/**
 * Worker message
 */
interface WorkerMessage {
  id: string;
  type: string;
  data: any;
}

/**
 * Execute agent query
 */
async function executeAgentQuery(message: WorkerMessage): Promise<any> {
  const { prompt, options } = message.data as {
    prompt: string;
    options?: AgentOptions;
  };

  try {
    logger.info('Worker executing query', { taskId: message.id });

    const results: string[] = [];

    // Execute query
    const queryResult = query({
      prompt,
      options: options as any,
    });

    // Collect results
    for await (const msg of queryResult) {
      if (msg.type === 'assistant') {
        const content = msg.content;
        if (Array.isArray(content)) {
          for (const block of content) {
            if (block.type === 'text') {
              results.push(block.text);
            }
          }
        }
      }
    }

    const result = results.join('\n');

    logger.info('Worker query completed', { taskId: message.id });

    return result;
  } catch (error) {
    logger.error('Worker query failed', { taskId: message.id, error });
    throw error;
  }
}

/**
 * Execute tool
 */
async function executeTool(message: WorkerMessage): Promise<any> {
  const { toolName, args } = message.data as {
    toolName: string;
    args: any;
  };

  try {
    logger.info('Worker executing tool', { taskId: message.id, toolName });

    // Tool execution logic would go here
    // For now, just return a placeholder

    logger.info('Worker tool completed', { taskId: message.id, toolName });

    return { success: true, toolName, args };
  } catch (error) {
    logger.error('Worker tool failed', { taskId: message.id, toolName, error });
    throw error;
  }
}

/**
 * Message handler
 */
self.onmessage = async (event: MessageEvent) => {
  const message = event.data as WorkerMessage;

  try {
    let result: any;

    switch (message.type) {
      case 'agent_query':
        result = await executeAgentQuery(message);
        break;

      case 'tool_execution':
        result = await executeTool(message);
        break;

      default:
        throw new Error(`Unknown task type: ${message.type}`);
    }

    // Send result back to main thread
    self.postMessage({
      id: message.id,
      result,
    });
  } catch (error) {
    // Send error back to main thread
    self.postMessage({
      id: message.id,
      error: error instanceof Error ? error.message : 'Unknown error',
    });
  }
};

// Log worker ready
logger.info('Agent worker ready');

